package cn.cangfei.massage.service.impl;

import cn.cangfei.massage.dto.update.AuthParamsDto;
import cn.cangfei.massage.entity.PowerAccount;
import cn.cangfei.massage.entity.UserBasicInfo;
import cn.cangfei.massage.service.IPowerAccountService;
import cn.cangfei.massage.service.AuthService;
import cn.cangfei.massage.service.IUserBasicInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 微信登录
 */

@Slf4j
@Service("wx_authservice")
public class WxAuthServiceImpl implements AuthService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private IUserBasicInfoService userBasicInfoService;

    @Resource
    private IPowerAccountService powerAccountService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void execute(AuthParamsDto authParamsDto) {
        // 得到openId
        String openId = authParamsDto.getOpenId();

        // 注意这里我得到的手机号不用判断

        // 看数据库里面是否有openId
        UserBasicInfo userBasicInfo = userBasicInfoService.getUserByOpenId(openId);
        // 如果没有就添加一个
        if (userBasicInfo == null) {
            // 添加一个用户
            UserBasicInfo userBasicInfoInsert = new UserBasicInfo();
            userBasicInfoInsert.setOpenId(openId);
            userBasicInfoInsert.setPhone(authParamsDto.getCellphone());
            userBasicInfoInsert.setAvatarUrl(authParamsDto.getUrl());
            userBasicInfoInsert.setName(authParamsDto.getUsername());
            // 存入孩子名字
            userBasicInfoInsert.setChild(authParamsDto.getChildName());
            userBasicInfoInsert.setGmtModified(new Date());
            userBasicInfoInsert.setGmtCreate(new Date());
            userBasicInfoService.save(userBasicInfoInsert);
        }

        // 先根据openId来查询account
        boolean count = powerAccountService.count(openId);
        if (!count) {
            PowerAccount powerAccount = new PowerAccount();
            powerAccount.setName(authParamsDto.getOpenId());
            powerAccount.setStatus(1);
            powerAccount.setGmtModified(new Date());
            powerAccount.setGmtCreate(new Date());
            powerAccount.setLoginTime(new Date());
            powerAccount.setPassword(passwordEncoder.encode("123456"));

            // 如果没有就添加一个
            powerAccountService.save(powerAccount);
        }
        // 还要给account表里面添加一个字段
        // name使用的是手机号

    }
}
